package fi.foyt.cs.persistence.dao.task;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.task.TaskRewardItem;

public class TaskRewardItemDAO extends GenericDAO<TaskRewardItem> {

  public TaskRewardItem create(Long taskRewardsId, Long itemId, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      TaskRewardItem taskRewardItem = new TaskRewardItem();
      taskRewardItem.setCount(count);
      taskRewardItem.setItemId(itemId);
      taskRewardItem.setTaskRewardsId(taskRewardsId);
      entityManager.persist(taskRewardItem);
      entityManager.getTransaction().commit();
      return taskRewardItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  @SuppressWarnings("unchecked")
  public List<TaskRewardItem> listByTaskRewardsId(Long taskRewardsId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from TaskRewardItem o where taskRewardsId = :taskRewardsId");
    query.setParameter("taskRewardsId", taskRewardsId);
    return query.getResultList();
  }

  public TaskRewardItem updateCount(TaskRewardItem taskRewardsItem, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      taskRewardsItem.setCount(count);
      taskRewardsItem = entityManager.merge(taskRewardsItem);
      entityManager.getTransaction().commit();

      return taskRewardsItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public TaskRewardItem updateItemId(TaskRewardItem taskRewardsItem, Long itemId) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      taskRewardsItem.setItemId(itemId);
      taskRewardsItem = entityManager.merge(taskRewardsItem);
      entityManager.getTransaction().commit();

      return taskRewardsItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
}
